angular.module('manageTeam', ['toastr', 'common'])
    .controller('manageTeamController',
        ['$scope', '$http', 'toastr', 'commonService',
            function ($scope, $http, toastr, commonService) {
                var mapping = null;
                var nonLeader = [];
                var nameRMap = {};
                var page = {1: 0, 2: 0};
                var total = {1: 0, 2: 0};
                var table = {1: [], 2: []};
                var size = 5;
                $scope.team = [];
                $scope.current = {};
                $scope.cursor = 0;
                if (!!$.cookie("toast")) {
                    toastr.success($.cookie("toast"));
                    $.cookie("toast", "");
                }

                (function initScope() {
                    $http.get('/user/mapping', {}).success(function (data) {
                        mapping = data;
                        nonLeader = [];
                        for (var i in mapping.name) {
                            if (mapping.role[i] == 'member') {
                                nameRMap[mapping.name[i]] = i;
                                nonLeader.push(mapping.name[i]);
                            }
                        }
                        $(".team-data").each(function () {
                            $scope.team.push({
                                t_name: $($(this).children()[0]).text().trim(),
                                leader: $($(this).children()[1]).val(),
                                description: $($(this).children()[2]).val(),
                                leaderName: mapping.name[parseInt($($(this).children()[1]).val())]
                            });
                        });
                        $scope.current = $scope.team[0];

                        $("#leader").autocomplete({
                            source: nonLeader,
                            select: function (event, ui) {
                                $scope.current.leaderName = ui.item.value;
                            }
                        });
                    });
                })();

                $scope.showTeam = function (id) {
                    $scope.cursor = id;
                    $scope.current = $scope.team[id];

                    $("#leader").attr("readonly", "readonly");

                    $(".team-data .active").removeClass("active");
                    $(".team-data-" + id).addClass("active");

                    $(".list-team").each(function () {
                        //$(this).css("display","none");
                        $(this).hide(200);
                    });
                    $(".team-" + id).each(function () {
                        //$(this).css("display","block");
                        $(this).show(200);
                    });
                };

                $scope.deleteTeam = function(id,e) {
                    e.stopPropagation();
                    commonService.modalPrompt("删除研发组将导致所有成员不属于任何研发组且无法恢复, 确认删除?",function(){
                        $http.post('/team/delete',{t_name : $scope.team[id].t_name}).success(function(data){
                            if(data == 'success') {
                                $.cookie("toast", "删除成功");
                                location.assign(window.location.href.split("?")[0]);
                            } else {
                                toastr.error("删除失败!"+data.description);
                            }
                        }).error(function(){
                            toastr.error("请检查网络连接");
                        })
                    });
                };

                $scope.saveTeam = function () {
                    var leaderId = nameRMap[$scope.team[$scope.cursor].leaderName];
                    if (mapping.name[$scope.team[$scope.cursor].leader] != $scope.team[$scope.cursor].leaderName && !leaderId) {
                        toastr.warning("研发组长输入有误");
                        return;
                    }
                    if (mapping.name[$scope.team[$scope.cursor].leader] != $scope.team[$scope.cursor].leaderName) {
                        $scope.team[$scope.cursor].leader = parseInt(leaderId);
                        $http.post("/team/update/leader", $scope.team[$scope.cursor]).success(function (data) {
                            if (data == "success") {
                                $.cookie("toast", "保存成功");
                                location.assign(window.location.href.split("?")[0] + "?location=" + $scope.cursor);
                            } else {
                                toastr.error("保存失败！" + data.description);
                            }
                        }).error(function () {
                            toastr.error("请检查网络连接");
                        });
                    } else {
                        if (!$scope.team[$scope.cursor].leader) {
                            toastr.warning("请指定研发组长");
                            return;
                        }
                        $http.post("/team/update", $scope.team[$scope.cursor]).success(function (data) {
                            if (data == "success") {
                                toastr.success("保存成功");
                            } else {
                                toastr.error("保存失败！" + data.description);
                            }
                        }).error(function () {
                            toastr.error("请检查网络连接");
                        });
                    }
                };

                $scope.newTeamModal = function () {
                    $(".new-team").modal();
                };

                $scope.saveNewTeam = function () {
                    var t_name = $("#t_name_new").val().trim();
                    validateUnique("'" + t_name + "'", "team", "t_name", function () {
                        var data = {
                            t_name: t_name,
                            description: $("#new_description").val() || t_name
                        };
                        $http.post("/team/add", data).success(function (data) {
                            if (data == 'success') {
                                window.location.href = window.location.href.split("?")[0] + "?location=new";
                                $.cookie("toast", "添加研发组成功");
                            } else {
                                toastr.error("新建失败!" + data.description);
                            }
                        }).error(function () {
                            toastr.error("请检查网络连接");
                        });
                    });
                };

                $scope.removeMember = function (id) {
                    commonService.modalPrompt("确认将该成员移出研发组?", function () {
                        $http.post('/user/fire', {id: id}).success(function (data) {
                            if (data == 'success') {
                                toastr.success("移除成功");
                                $("#team-" + $scope.cursor + "-" + id).remove();
                            } else {
                                toastr.error("移除失败!" + data.description);
                            }
                        }).error(function () {
                            toastr.error("请检查网络连接");
                        })
                    });
                };

                $scope.changeLeader = function () {
                    if (!$scope.current.leaderName) {
                        $("#leader").removeAttr("readonly");
                        $("#leader").focus();
                        return;
                    }
                    commonService.modalPrompt("&nbsp;&nbsp;&nbsp;&nbsp;更改研发组长后:<br />" +
                        "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.原研发组长将不属于任何研发组<br />" +
                        "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.由新组长接受通知和填写计划,<br />" +
                        "<br />&nbsp;&nbsp;&nbsp;&nbsp;确认更改?",
                        function () {
                            $("#leader").removeAttr("readonly");
                            $("#leader").focus();
                        });
                };

                $scope.addMember = function () {
                    var selectIds = [];
                    table[1].forEach(function (e) {
                        if (e.checked) {
                            selectIds.push(e.u_id);
                        }
                    });
                    table[2].forEach(function (e) {
                        if (e.checked) {
                            selectIds.push(e.u_id);
                        }
                    });
                    if (selectIds.length == 0) {
                        toastr.warning("未选择任何用户");
                        return;
                    }
                    var t_name = $scope.team[$scope.cursor].t_name;
                    $http.post('/team/addMember', {id: selectIds, team: t_name}).success(function (data) {
                        if (data == "success") {
                            $.cookie("toast", "保存成功");
                            window.location.href = window.location.href.split("?")[0] + "?location=" + $scope.cursor;
                        } else {
                            toastr.error("保存失败！" + data.description);
                        }
                    }).error(function () {
                        toastr.error("请检查网络连接");
                    });
                };

                $scope.previousPage = function (type) {
                    if (page[type] > 0) {
                        --page[type];
                        buildList(type, page[type] * size, (page[type] + 1) * size);
                    } else {
                        toastr.warning("已经是第一页");
                    }
                };
                $scope.nextPage = function (type) {
                    if (table[type][page[type] * size + size]) {
                        ++page[type];
                        buildList(type, page[type] * size, (page[type] + 1) * size);
                    } else {
                        toastr.warning("已经是最后一页");
                    }
                };

                function buildList(type, start, end) {
                    $(".table-data-" + type).each(function () {
                        $(this).remove();
                    });
                    var html = "";
                    for (var i = start; i < end; i++) {
                        if (!table[type][i]) break;
                        var checked = "";
                        if (table[type][i].checked) {
                            checked = 'checked';
                        }
                        html += '<tr class="table-data-' + type + '">\
                            <td><input onclick="selectUser(this)" type="checkbox" ' + checked + ' id="select-' + type + '-' + i + '" /></td>\
                            <td>' + table[type][i].username + '</td>\
                            <td>' + table[type][i].u_name + '</td>\
                            </tr>';
                    }
                    $(".table-" + type).append(html);
                }

                function validateUnique(value, schema, attr, cb) {
                    $http.post('/validate/unique', {value: value, schema: schema, attr: attr}).success(function (data) {
                        if (data === 'success') {
                            cb(true);
                        } else if (data === 'fail') {
                            cb(false);
                        } else {
                            toastr.error("服务器出错");
                        }
                    });
                }

                window.selectUser = function (element) {
                    var temp = $(element).attr("id").split("-");
                    if ($(element).is(":checked")) {
                        table[temp[1]][temp[2]].checked = true;
                    } else {
                        table[temp[1]][temp[2]].checked = false;
                    }
                };

                $("#addMember").click(function () {
                    table = {1: [], 2: []};
                    page = {1: 0, 2: 0};
                    $http.post('/member/find', {role: ['member', 'intern']}).success(function (data) {
                        data.forEach(function (e) {
                            !e.team ? table['1'].push(e) : table['2'].push(e);
                        });
                        total['1'] = table['1'].length / size + (table['1'].length % size ? 1 : 0);
                        total['2'] = table['2'].length / size + (table['2'].length % size ? 1 : 0);
                        buildList(1, 0, size);
                        buildList(2, 0, size);
                        $(".member-modal").modal();
                    });
                });

                $(document).ready(function () {
                    if (window.location.href.split("?").length == 2) {
                        var locationTemp = window.location.href.split("?")[1].split("=")[1];
                        setTimeout(function () {
                            if (locationTemp == 'new') {
                                $scope.team.forEach(function (e, i) {
                                    if (!e.leader) {
                                        locationTemp = i;
                                    }
                                });
                            }
                            $(".team-data-" + locationTemp).click();
                        }, 50);
                    } else {
                        $(".team-data-0").addClass("active");
                    }
                });
            }
        ]);